<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <!-- 基本信息 tab -->
      <el-tab-pane label="基本资料" name="basic">
        <el-row :gutter="20">
          <!-- 左侧表单 -->
          <el-col :span="12">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
              <el-form-item label="设备名称" prop="deviceName">
                <el-input v-model="form.deviceName" placeholder="请输入设备名称" :disabled="true" />
              </el-form-item>
              <el-form-item label="所属产品" prop="productId">
                <el-select v-model="form.productId" placeholder="请选择所属产品" :disabled="true">
                  <el-option
                    v-for="item in productOptions"
                    :key="item.id"
                    :label="item.productName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="设备编号" prop="deviceCode">
                <el-input v-model="form.deviceCode" placeholder="请输入设备编号" :disabled="true" />
              </el-form-item>
              <el-form-item label="固件版本" prop="firmwareVersion">
                <el-input v-model="form.firmwareVersion" placeholder="请输入固件版本" :disabled="true" />
              </el-form-item>
              <el-form-item label="设备状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择设备状态" :disabled="true">
                  <el-option label="未激活" :value="1" />
                  <el-option label="禁用" :value="2" />
                  <el-option label="在线" :value="3" />
                  <el-option label="离线" :value="4" />
                </el-select>
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="true" />
              </el-form-item>
            </el-form>
          </el-col>
          <!-- 右侧地图 -->
          <el-col :span="12">
            <div class="map-container">
              <!-- <baidu-map 
                :longitude="mapCenter.lng"
                :latitude="mapCenter.lat"
                :zoom="15"
                :editable="false"
                style="height: 500px;"
                v-loading="mapLoading"
              /> -->
              <a-map
                ref="aMap"
                :longitude="mapCenter.lng"
                :latitude="mapCenter.lat"
                :zoom="15"
                :editable="false"
                style="height: 500px;"
                v-loading="mapLoading"
              />
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 运行状态 tab -->
      <el-tab-pane label="运行状态" name="status">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card class="status-card">
              <div slot="header">
                <span>设备状态</span>
              </div>
              <div class="status-content">
                <el-tag :type="getStatusType(form.status)">{{ getStatusText(form.status) }}</el-tag>
                <div class="status-time">最后上线时间：{{ parseTime(form.activeTime) }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="status-card">
              <div slot="header">
                <span>运行时长</span>
              </div>
              <div class="status-content">
                <span class="status-value">{{ runningTime }}</span>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="status-card">
              <div slot="header">
                <span>通信状态</span>
              </div>
              <div class="status-content">
                <el-tag :type="form.status === 3 ? 'success' : 'danger'">
                  {{ form.status === 3 ? '通信正常' : '通信异常' }}
                </el-tag>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 实时监测 -->
      <el-tab-pane label="实时监测" name="monitoring">
        <el-row :gutter="15">
          <el-col :span="24">
            <el-button style="float: right; margin-bottom: 15px;" type="primary" plain size="mini" @click="refreshMonitorData">
              <i class="el-icon-refresh"></i> 刷新数据
            </el-button>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :lg="6" :md="8" :sm="12" :xs="24" v-for="item in monitorData" :key="item.modelCode">
            <el-card shadow="hover" class="monitor-card" :class="{ 'status-abnormal': item.status !== 'normal' }">
              <div class="monitor-header">
                <div class="monitor-title">
                  <span class="monitor-name">{{ item.modelName }}</span>
                  <el-tag size="mini" effect="plain">{{ item.modelCode }}</el-tag>
                </div>
                <div class="monitor-status">
                  <el-tag size="mini" :type="item.status === 'normal' ? 'success' : 'danger'" effect="dark">
                    {{ item.status === 'normal' ? '正常' : '异常' }}
                  </el-tag>
                </div>
              </div>
              <div class="monitor-body">
                <div class="monitor-value">
                  <span class="value" :class="{ 'text-danger': item.status !== 'normal' }">{{ item.value }}</span>
                  <span class="unit" v-if="getUnitFromDataDefine(item)">{{ getUnitFromDataDefine(item) }}</span>
                </div>
              </div>
              <div class="monitor-footer">
                <div class="monitor-time">
                  <i class="el-icon-time"></i>
                  <span>{{ parseTime(item.ts) }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>

      <!-- 设备告警 tab -->
      <el-tab-pane label="设备告警" name="alarm">
        <el-table v-loading="alarmLoading" :data="alarmData">
          <el-table-column label="告警时间" prop="alarmTime">
            <template slot-scope="scope">
              {{ parseTime(scope.row.alarmTime) }}
            </template>
          </el-table-column>
          <el-table-column label="告警类型" prop="alarmType" />
          <el-table-column label="告警内容" prop="alarmContent" />
          <el-table-column label="告警等级" prop="alarmLevel">
            <template slot-scope="scope">
              <el-tag :type="getAlarmLevelType(scope.row.alarmLevel)">
                {{ getAlarmLevelText(scope.row.alarmLevel) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="处理状态" prop="processStatus">
            <template slot-scope="scope">
              <el-tag :type="scope.row.processStatus ? 'success' : 'warning'">
                {{ scope.row.processStatus ? '已处理' : '未处理' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 监测统计 tab -->
      <el-tab-pane label="监测统计" name="statistics">
        <div class="chart-container">
          <div id="statisticsChart" style="width: 100%; height: 400px;"></div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <div class="bottom-button">
      <el-button @click="cancel">返回</el-button>
    </div>
  </div>
</template>

<script>
import { getDevice } from "@/api/iot/device";
import { listProduct } from "@/api/iot/product";
import { getProductModel } from "@/api/iot/model";
import { getDeviceLatestData } from "@/api/iot/data";
import * as echarts from 'echarts'
import BaiduMap from '@/components/BaiduMap'
import AMap from "@/components/AMap";

export default {
  name: "DeviceView",
  components: {
    BaiduMap,
    AMap
  },
  data() {
    return {
      // 激活的tab页签
      activeTab: 'basic',
      // 表单参数
      form: {},
      // 产品选项
      productOptions: [],
      // 表单校验
      rules: {
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "所属产品不能为空", trigger: "change" }
        ]
      },
      // 运行时长
      runningTime: '0天0小时0分钟',
      // 监测数据加载状态
      monitorLoading: false,
      // 监测数据
      monitorData: [],
      // 告警数据加载状态
      alarmLoading: false,
      // 告警数据
      alarmData: [],
      // 图表实例
      statisticsChart: null,
      // 定时刷新定时器
      monitorTimer: null,
      // 物模型列表
      modelList: [],
      // 地图相关数据
      mapCenter: {
        lng: 116.404,
        lat: 39.915
      },
      // 添加地图加载状态
      mapLoading: false
    };
  },
  created() {
    const id = this.$route.query.id;
    if (id) {
      this.getInfo(id);
      this.refreshMonitorData();
    }
    this.getProductOptions();
    // 模拟获取告警数据
    this.getAlarmData();
  },
  mounted() {
    // 初始化统计图表
    this.initStatisticsChart();
    // 启动定时刷新
    this.startMonitorTimer();
  },
  beforeDestroy() {
    if (this.statisticsChart) {
      this.statisticsChart.dispose();
    }
    // 清除定时器
    this.clearMonitorTimer();
  },
  methods: {
    /** 获取设备详细信息 */
    async getInfo(id) {
      try {
        const response = await getDevice(id);
        console.log('设备信息:', response.data);
        this.form = response.data;
        
        // 设置地图中心点
        if (response.data) {
          // 检查经纬度是否存在且有效
          const longitude = parseFloat(response.data.longitude);
          const latitude = parseFloat(response.data.latitude);
          
          console.log('设备位置信息:', { longitude, latitude });
          
          if (!isNaN(longitude) && !isNaN(latitude) && 
              longitude >= -180 && longitude <= 180 && 
              latitude >= -90 && latitude <= 90) {
            this.mapCenter = {
              lng: longitude,
              lat: latitude
            };
            console.log('设置地图中心点:', this.mapCenter);
          } else {
            console.warn('设备经纬度数据无效或不存在:', { longitude, latitude });
            this.$message.warning('设备位置信息不完整或无效');
            // 设置默认位置（可以根据需要修改）
            this.mapCenter = {
              lng: 116.404,
              lat: 39.915
            };
          }
        }
        
        // 获取物模型信息
        if (this.form.productId) {
          console.log('获取物模型, productId:', this.form.productId);
          const modelRes = await getProductModel(this.form.productId);
          console.log('物模型响应:', modelRes);
          if (modelRes.rows && modelRes.rows.length > 0) {
            // 过滤出类型为property且is_monitor为1的物模型
            this.modelList = modelRes.rows.filter(item => 
              item.modelType === 'property' && item.isMonitor === true
            );
            console.log('过滤后的物模型列表:', this.modelList);
          }
        }
        // 计算运行时长
        this.calculateRunningTime();
      } catch (error) {
        console.error('获取设备信息失败:', error);
        this.$modal.msgError('获取设备信息失败：' + error.message);
      }
    },
    /** 获取产品选项列表 */
    getProductOptions() {
      listProduct().then(response => {
        this.productOptions = response.rows;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.$router.push({ path: "/iot/device" });
    },
    /** 获取状态显示文本 */
    getStatusText(status) {
      const statusMap = {
        1: '未激活',
        2: '禁用',
        3: '在线',
        4: '离线'
      };
      return statusMap[status] || '未知';
    },
    /** 获取状态显示类型 */
    getStatusType(status) {
      const typeMap = {
        1: 'info',
        2: 'danger',
        3: 'success',
        4: 'warning'
      };
      return typeMap[status] || '';
    },
    /** 计算运行时长 */
    calculateRunningTime() {
      if (this.form.activeTime) {
        const now = new Date();
        const activeTime = new Date(this.form.activeTime);
        const diff = now - activeTime;
        const days = Math.floor(diff / (24 * 60 * 60 * 1000));
        const hours = Math.floor((diff % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000));
        const minutes = Math.floor((diff % (60 * 60 * 1000)) / (60 * 1000));
        this.runningTime = `${days}天${hours}小时${minutes}分钟`;
      }
    },
    /** 获取监测数据 */
    async getMonitorData() {
      if (!this.form.deviceCode || this.modelList.length === 0) {
        return;
      }
      this.monitorLoading = true;
      try {
        const response = await getDeviceMonitoring(this.form.deviceCode);
        console.log('监测数据响应:', response);
        if (response.data && Array.isArray(response.data)) {
          // 将监测数据与物模型信息合并
          this.monitorData = this.modelList.map(model => {
            const latestData = response.data.find(item => item.key === model.modelCode);
            let value = '-';
            
            if (latestData) {
              // 根据不同的值类型获取对应的值
              if (latestData.boolValue !== null) {
                value = latestData.boolValue;
              } else if (latestData.strValue !== null) {
                value = latestData.strValue;
              } else if (latestData.longValue !== null) {
                value = latestData.longValue;
              } else if (latestData.doubleValue !== null) {
                value = latestData.doubleValue;
              } else if (latestData.jsonValue !== null) {
                value = JSON.stringify(latestData.jsonValue);
              } else if (latestData.value !== undefined) {
                value = latestData.value;
              }
            }

            return {
              modelName: model.modelName,
              modelCode: model.modelCode,
              value: value,
              unit: model.unit || '',
              dataDefine: model.dataDefine || '',
              ts: latestData ? latestData.ts : null,
              status: latestData ? (latestData.status || 'normal') : 'normal'
            };
          });
          console.log('处理后的监测数据:', this.monitorData);
        }
      } catch (error) {
        console.error('获取监测数据失败:', error);
      } finally {
        this.monitorLoading = false;
      }
    },
    /** 刷新监测数据 */
    async refreshMonitorData() {
      console.log('开始刷新监测数据');
      console.log('设备编号:', this.form.deviceCode);
      console.log('物模型列表:', this.modelList);
      
      if (!this.form.deviceCode) {
        console.warn('设备编号为空，无法刷新数据');
        return;
      }
      
      // 如果物模型列表为空，先获取物模型
      if ((!this.modelList || this.modelList.length === 0) && this.form.productId) {
        console.log('物模型列表为空，先获取物模型');
        try {
          const modelRes = await getProductModel(this.form.productId);
          console.log('物模型响应:', modelRes);
          if (modelRes.rows && modelRes.rows.length > 0) {
            this.modelList = modelRes.rows.filter(item => 
              item.modelType === 'property' && item.isMonitor === true
            );
            console.log('获取到的物模型列表:', this.modelList);
          }
        } catch (error) {
          console.error('获取物模型失败:', error);
          return;
        }
      }
      
      this.monitorLoading = true;
      try {
        const response = await getDeviceLatestData(this.form.deviceCode);
        console.log('监测数据响应:', response);
        
        if (response.data && Array.isArray(response.data)) {
          // 将监测数据与物模型信息合并
          this.monitorData = this.modelList.map(model => {
            console.log('处理物模型:', model);
            const latestData = response.data.find(item => item.key === model.modelCode);
            console.log('找到的最新数据:', latestData);
            let value = '-';
            
            if (latestData) {
              // 根据不同的值类型获取对应的值
              if (latestData.longValue !== null && latestData.longValue !== undefined) {
                value = latestData.longValue;
              } else if (latestData.doubleValue !== null && latestData.doubleValue !== undefined) {
                value = latestData.doubleValue;
              } else if (latestData.strValue !== null && latestData.strValue !== undefined) {
                value = latestData.strValue;
              } else if (latestData.boolValue !== null && latestData.boolValue !== undefined) {
                value = latestData.boolValue;
              } else if (latestData.jsonValue !== null && latestData.jsonValue !== undefined) {
                value = JSON.stringify(latestData.jsonValue);
              } else if (latestData.value !== undefined) {
                value = latestData.value;
              }
              console.log('解析后的值:', value);
            }

            const result = {
              modelName: model.modelName || model.modelCode,
              modelCode: model.modelCode,
              value: value,
              dataDefine: model.dataDefine || '',
              ts: latestData ? latestData.ts : null,
              status: latestData ? (latestData.status || 'normal') : 'normal'
            };
            console.log('生成的监测数据项:', result);
            return result;
          });
          console.log('最终的监测数据列表:', this.monitorData);
        }
      } catch (error) {
        console.error('刷新监测数据失败:', error);
        this.$modal.msgError('获取监测数据失败：' + error.message);
      } finally {
        this.monitorLoading = false;
      }
    },
    /** 启动定时刷新 */
    startMonitorTimer() {
      this.monitorTimer = setInterval(() => {
        if (this.activeTab === 'monitoring') {
          this.refreshMonitorData();
        }
      }, 30000); // 每30秒刷新一次
    },
    /** 清除定时器 */
    clearMonitorTimer() {
      if (this.monitorTimer) {
        clearInterval(this.monitorTimer);
        this.monitorTimer = null;
      }
    },
    /** 模拟获取告警数据 */
    getAlarmData() {
      this.alarmLoading = true;
      setTimeout(() => {
        this.alarmData = [
          { 
            alarmTime: new Date(),
            alarmType: '温度告警',
            alarmContent: '设备温度超过阈值',
            alarmLevel: 1,
            processStatus: false
          },
          {
            alarmTime: new Date(Date.now() - 24 * 60 * 60 * 1000),
            alarmType: '通信告警',
            alarmContent: '设备离线',
            alarmLevel: 2,
            processStatus: true
          }
        ];
        this.alarmLoading = false;
      }, 1000);
    },
    /** 获取告警等级显示文本 */
    getAlarmLevelText(level) {
      const levelMap = {
        1: '一般',
        2: '严重',
        3: '紧急'
      };
      return levelMap[level] || '未知';
    },
    /** 获取告警等级显示类型 */
    getAlarmLevelType(level) {
      const typeMap = {
        1: 'warning',
        2: 'danger',
        3: 'danger'
      };
      return typeMap[level] || 'info';
    },
    /** 初始化统计图表 */
    initStatisticsChart() {
      this.statisticsChart = echarts.init(document.getElementById('statisticsChart'));
      const option = {
        title: {
          text: '设备监测数据统计'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['温度', '湿度', '电压']
        },
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '温度',
            type: 'line',
            data: [23, 24, 25, 26, 25, 24, 23]
          },
          {
            name: '湿度',
            type: 'line',
            data: [65, 63, 68, 64, 65, 67, 66]
          },
          {
            name: '电压',
            type: 'line',
            data: [220, 221, 219, 220, 220, 221, 220]
          }
        ]
      };
      this.statisticsChart.setOption(option);
    },
    /** 获取单位 */
    getUnitFromDataDefine(item) {
      console.log('获取单位:', item);
      try {
        if (item.dataDefine) {
          const defineObj = JSON.parse(item.dataDefine);
          return defineObj.unit || '';
        }
        return '';
      } catch (error) {
        console.error('解析 dataDefine 失败:', error);
        return '';
      }
    }
  },
  watch: {
    activeTab(newVal, oldVal) {
      if (newVal === 'monitoring' && oldVal !== 'monitoring') {
        // 切换到监测页签时刷新数据
        this.refreshMonitorData();
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #fff;
}

.el-form {
  max-width: 800px;
  margin: 0 auto;
  padding-top: 20px;
}

.bottom-button {
  margin-top: 20px;
  text-align: center;
}

.status-card {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  color: #303133;
  transition: .3s;
}

.status-content {
  text-align: center;
  padding: 20px 0;
}

.status-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.status-time {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}

.chart-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

/* 自定义 tab 样式 */
:deep(.el-tabs__nav-wrap) {
  background-color: #f5f7fa;
  padding: 0 20px;
}

:deep(.el-tabs__item) {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  color: #606266;
  position: relative;
  padding: 0 20px !important;
}

:deep(.el-tabs__item.is-active) {
  background-color: #fff;
  border-top: 2px solid #409EFF;
  color: #409EFF;
  padding-bottom: 0;
  border-bottom: none;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: #e4e7ed;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.el-tabs__content) {
  padding: 20px;
  background-color: #fff;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.monitor-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.monitor-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.monitor-card.status-abnormal {
  border: 1px solid #f56c6c;
}

.monitor-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.monitor-title {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.monitor-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 180px;
}

.monitor-status {
  display: flex;
  align-items: center;
}

.monitor-body {
  padding: 20px 15px;
  text-align: center;
  background-color: #fafafa;
  min-height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.monitor-value {
  display: flex;
  align-items: baseline;
  justify-content: center;
  flex-wrap: wrap;
}

.value {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  line-height: 1.4;
  transition: color 0.3s ease;
}

.value.text-danger {
  color: #f56c6c;
}

.unit {
  margin-left: 6px;
  font-size: 14px;
  color: #909399;
}

.monitor-footer {
  padding: 12px 15px;
  background: #fff;
}

.monitor-time {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  color: #909399;
  font-size: 13px;
}

.monitor-time i {
  font-size: 12px;
}

/* 添加一些动画效果 */
@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.01);
  }
  100% {
    transform: scale(1);
  }
}

.status-abnormal .value {
  animation: pulse 2s infinite;
}

.map-container {
  background: #fff;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form {
  max-width: 100%;
  margin: 0;
  padding-top: 0;
}
</style> 